#!/bin/bash

# Java应用部署脚本
# 部署到阿里云服务器 8.130.127.211

set -e  # 遇到错误立即停止

SERVER_IP="8.130.127.211"
SERVER_USER="root"
APP_NAME="game-training-platform"
APP_DIR="/opt/gameplatform"
JAR_FILE="kuangjia/target/game-training-platform-1.0.0.jar"

echo "🚀 开始部署Java应用到服务器..."

# 1. 检查本地jar包是否存在
if [ ! -f "$JAR_FILE" ]; then
    echo "❌ JAR包不存在: $JAR_FILE"
    echo "请先执行: mvn clean package -DskipTests"
    exit 1
fi

echo "✅ 找到JAR包: $JAR_FILE"

# 2. 创建临时部署目录
TEMP_DIR=$(mktemp -d)
echo "📁 创建临时目录: $TEMP_DIR"

# 3. 复制部署文件
cp "$JAR_FILE" "$TEMP_DIR/app.jar"
cp "java-api.conf" "$TEMP_DIR/"

# 4. 创建启动脚本
cat > "$TEMP_DIR/start.sh" << 'EOF'
#!/bin/bash
cd /opt/gameplatform

export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
export PATH=$JAVA_HOME/bin:$PATH

# 停止现有进程
if [ -f app.pid ]; then
    OLD_PID=$(cat app.pid)
    if kill -0 $OLD_PID 2>/dev/null; then
        echo "停止现有进程: $OLD_PID"
        kill $OLD_PID
        sleep 5
    fi
    rm -f app.pid
fi

# JVM参数
JVM_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -Dfile.encoding=UTF-8"

# 应用配置
APP_OPTS="--server.port=8084 --spring.profiles.active=prod"

# 启动应用
nohup java $JVM_OPTS -jar app.jar $APP_OPTS > app.log 2>&1 &
APP_PID=$!

echo $APP_PID > app.pid
echo "✅ 应用启动成功, PID: $APP_PID"
echo "📋 日志文件: /opt/gameplatform/app.log"
EOF

# 5. 创建systemd服务文件
cat > "$TEMP_DIR/gameplatform.service" << 'EOF'
[Unit]
Description=Game Training Platform Spring Boot Application
After=network.target

[Service]
Type=forking
User=root
WorkingDirectory=/opt/gameplatform
ExecStart=/opt/gameplatform/start.sh
ExecStop=/bin/bash -c 'if [ -f /opt/gameplatform/app.pid ]; then kill $(cat /opt/gameplatform/app.pid); fi'
PIDFile=/opt/gameplatform/app.pid
Restart=always
RestartSec=10
TimeoutStartSec=60

[Install]
WantedBy=multi-user.target
EOF

# 6. 创建部署脚本
cat > "$TEMP_DIR/deploy.sh" << 'EOF'
#!/bin/bash
set -e

echo "🔧 开始服务器端部署..."

# 安装Java 17 (如果需要)
if ! java -version 2>&1 | grep -q "17\|21"; then
    echo "📦 安装Java 17..."
    yum update -y
    yum install -y java-17-openjdk java-17-openjdk-devel
fi

# 创建应用目录
mkdir -p /opt/gameplatform
cd /opt/gameplatform

# 备份现有文件
if [ -f app.jar ]; then
    echo "📦 备份现有应用..."
    cp app.jar app.jar.backup.$(date +%Y%m%d_%H%M%S)
fi

# 复制新文件
echo "📂 复制应用文件..."
cp /tmp/deploy/app.jar .
cp /tmp/deploy/start.sh .
chmod +x start.sh

# 配置systemd服务
echo "⚙️  配置系统服务..."
cp /tmp/deploy/gameplatform.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable gameplatform

# 配置nginx
echo "🌐 配置Nginx..."
cp /tmp/deploy/java-api.conf /etc/aa_nginx/sites-available/
aa_nginx -t

# 启用nginx站点
if aa-site-enable java-api 2>/dev/null; then
    echo "✅ Nginx站点已启用"
else
    echo "🔗 手动创建nginx软链接..."
    ln -sf /etc/aa_nginx/sites-available/java-api.conf /etc/aa_nginx/sites-enabled/
    systemctl reload aa_nginx
fi

# 启动应用
echo "🚀 启动应用服务..."
systemctl restart gameplatform

# 等待启动
echo "⏳ 等待应用启动..."
sleep 10

# 检查状态
echo "🔍 检查服务状态..."
systemctl status gameplatform --no-pager

# 检查端口
if ss -tlnp | grep -q ":8084"; then
    echo "✅ 应用端口8084已启动"
else
    echo "❌ 应用端口8084未启动"
    tail -20 /opt/gameplatform/app.log
    exit 1
fi

# 测试API
echo "🧪 测试API连接..."
if curl -s -f http://127.0.0.1:8084/api/actuator/health >/dev/null; then
    echo "✅ 本地API健康检查通过"
else
    echo "❌ 本地API健康检查失败"
fi

# 测试nginx代理
if curl -s -f http://127.0.0.1/game-health >/dev/null; then
    echo "✅ Nginx代理健康检查通过"
else
    echo "❌ Nginx代理健康检查失败"
fi

echo "🎉 部署完成！"
echo "📋 代练通游戏平台访问地址:"
echo "   API地址: http://8.130.127.211/game-api/"
echo "   API文档: http://8.130.127.211/game-docs/"
echo "   健康检查: http://8.130.127.211/game-health"
echo "   支付回调: http://8.130.127.211/game-api/payment/wechat/notify"
echo "📋 应用日志: tail -f /opt/gameplatform/app.log"
echo "📋 Nginx日志: tail -f /var/log/nginx/game-platform-access.log"
EOF

chmod +x "$TEMP_DIR/deploy.sh"

echo "📤 上传文件到服务器..."

# 7. 上传文件到服务器
scp -r "$TEMP_DIR" "$SERVER_USER@$SERVER_IP:/tmp/deploy"

echo "🔧 在服务器上执行部署..."

# 8. 在服务器上执行部署
ssh "$SERVER_USER@$SERVER_IP" "chmod +x /tmp/deploy/deploy.sh && /tmp/deploy/deploy.sh"

# 9. 清理临时文件
rm -rf "$TEMP_DIR"

echo ""
echo "🎉 部署完成！"
echo ""
echo "📋 代练通游戏平台访问信息:"
echo "   API地址: http://$SERVER_IP/game-api/"
echo "   API文档: http://$SERVER_IP/game-docs/"
echo "   健康检查: http://$SERVER_IP/game-health"
echo "   支付回调: http://$SERVER_IP/game-api/payment/wechat/notify"
echo ""
echo "📋 管理命令:"
echo "   查看状态: ssh $SERVER_USER@$SERVER_IP 'systemctl status gameplatform'"
echo "   查看日志: ssh $SERVER_USER@$SERVER_IP 'tail -f /opt/gameplatform/app.log'"
echo "   重启应用: ssh $SERVER_USER@$SERVER_IP 'systemctl restart gameplatform'"
echo ""
